
int pin[3] = {A0, A4, A3};           //从左至右对应
int velocity;                        //定义速率
byte value;
byte value_his = 0; //记录上一次的传感器值
void setup()
{
  pinMode( 5 , OUTPUT);
  pinMode( 6 , OUTPUT);
  pinMode( 9 , OUTPUT);
  pinMode( 10 , OUTPUT);
}

void loop()
{

   value = 0;
        for(int i=0; i<3; i++)
        {
            value |= (digitalRead(pin[i]) << i);
        }
        if(value == 0x07)
        { //当传感器都没有触发时默认为上一次的值
          value = value_his;
        }
        switch (value) 
        {
          case 0x00: //全部触发
          Forwards();
          break;
          case 0x01: //触发右边两个
          while(digitalRead(pin[1])){ //通过while 循环使小车回到跑道中间
          Right();
        }
        break;
        case 0x03: //触发右边一个
        while(digitalRead(pin[1]))
        {
          Right();
        }
        break;
        case 0x04: //触发左边两个
          while(digitalRead(pin[1]))
          {
            Left();
          }
        break;
        case 0x05: //触发中间一个
          Forwards();
          break;
        case 0x06: //触发左边一个
          while(digitalRead(pin[1]))
          {
          Left();
          }
          break;
          default:
          Stop();
        }
        value_his = value;

  }
 
void Left()
{
analogWrite( 5 , velocity );
analogWrite( 6 , 0 );
analogWrite( 9 , 0 );
analogWrite( 10 , 0 );
}

void Right()
{
analogWrite( 5 , 0 );
analogWrite( 6 , 0 );
analogWrite( 9 , velocity );
analogWrite( 10 , 0 );
}

void Forwards()
{
analogWrite( 5 , velocity );
analogWrite( 6 , 0 );
analogWrite( 9 , velocity );
analogWrite( 10 , 0 );
}

void Stop()
{
analogWrite( 5 , 0 );
analogWrite( 6 , 0 );
analogWrite( 9 , 0 );
analogWrite( 10 , 0 );
}
